import Vue from 'vue'
import VueRouter from 'vue-router'

// import Login from '@/views/login'
// import myorder from '@/views/myorder'
// import pay from '@/views/pay'
// import search from '@/views/search'
// import searchList from '@/views/search/list'
// import prodetail from '@/views/prodetail'
// 二级路由
import layout from '@/views/layout'
import cart from '@/views/layout/cart'
import home from '@/views/layout/home'
import user from '@/views/layout/user'
import categroy from '@/views/layout/categroy'

import store from '@/store'

const Login = () => import('@/views/login')
const myorder = () => import('@/views/myorder')
const pay = () => import('@/views/pay')
const search = () => import('@/views/search')
const searchList = () => import('@/views/search/list')
const prodetail = () => import('@/views/prodetail')
Vue.use(VueRouter)
const router = new VueRouter({
  routes: [
    { path: '/login', component: Login },
    {
      path: '/',
      component: layout,
      redirect: '/home',
      children: [
        { path: '/home', component: home },
        { path: '/cart', component: cart },
        { path: '/user', component: user },
        { path: '/categroy', component: categroy }
      ]
    },
    { path: '/myorder', component: myorder },
    { path: '/pay', component: pay },
    { path: '/search', component: search },
    { path: '/searchList', component: searchList },
    // 动态传参，确定是哪个商品
    { path: '/prodetail/:id', component: prodetail }
  ]
})
// 全局前置导航守卫
// const router = createRouter({ ... })
const authUrl = ['/pay', '/myorder'] // 需要权限的访问页面
router.beforeEach((to, from, next) => {
  // 返回 false 以取消导航
  if (!authUrl.includes(to.path)) {
    next()
    return
  }
  const token = store.getters.token
  if (token) {
    next()
  } else {
    next('/login')
  }
})

export default router
